// pages/selectStore/selectStore.js
const util = require('../../../utils/utils.js')
const storeService = require('../../../api/storeService.js')

//获取应用实例
const app = getApp()

var QQMapWX = require('../../../libs/qqmap-wx-jssdk.min.js');
var qqmapsdk;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchLabelShow: false,
    searchText: '搜索门店',
    currentAddress: '',
    storeList: [],
    allStoreList: [],
    page: 0,
    loading: true,
    noStoreData: false,
    refresh: false,
  },

  // 搜索框点击事件,输入框聚焦
  handleFocus: function (e) {
    this.setData({
      searchLabelShow: true
    })
  },
  // 搜索框失去焦点处理
  handleBlur: function (e) {
    if (!e.detail.value) {
      this.setData({
        searchLabelShow: false
      })
    } else {
      this.setData({
        searchLabelShow: true
      })
    }
  },
  // 拿到缓存中的所有门店，然后计算距离，进行排序
  hadleStoreOrder: function (latitude, longitude) {
    try {
      var allStores = wx.getStorageSync('_allStores_'); // 获取缓存的所有门店
      var distanceArr = [];
      var newArr = [];
      allStores.forEach(item => {
        let dis = util.distance(latitude, longitude, item.latitude, item.longitude);
        distanceArr.push({
          distance: dis,
          id: item.id
        });
      })
      newArr = [].concat(distanceArr); // newArr为一个新的数组，不是简单的赋值引用
      function compare(property) {
        return function (a, b) {
          var value1 = a[property];
          var value2 = b[property];
          return value1 - value2;
        }
      }
      newArr.sort(compare('distance')); // newArr已经按照从小到大的顺序进行排列, 根据对象中的distance属性进行排序

      // 将allStores中的信息进行排列，按照距离从小到大的顺序
      var newTempAllStore = [];
      for (let i = 0; i < newArr.length; i++) {
        for (let j = 0; j < distanceArr.length; j++) {
          if (newArr[i].id == distanceArr[j].id) {
            allStores[j].distance = newArr[i].distance; // 加入距离参数
            newTempAllStore.push(allStores[j]); // j的顺序与allStore中的数据顺序一致 
          }
        }
      }
      try {
        wx.setStorageSync('wj_allStores', newTempAllStore)
      } catch (e) {
        console.log(e)
      }
      var tempData = [];
      for (let i = 0; i < newTempAllStore.length; i++) {
        if (app.globalData.storeInfo && app.globalData.storeInfo.id == newTempAllStore[i].id) {
          //tempData.push(app.globalData.storeInfo)
          tempData.push({
            id: newTempAllStore[i].id,
            name: newTempAllStore[i].name,
            address: newTempAllStore[i].address,
            distance: newArr[i].distance.toFixed(2),
            latitude: newTempAllStore[i].latitude,
            longitude: newTempAllStore[i].longitude,
            active: true
          })
        } else {
          tempData.push({
            id: newTempAllStore[i].id,
            name: newTempAllStore[i].name,
            address: newTempAllStore[i].address,
            distance: newArr[i].distance.toFixed(2),
            latitude: newTempAllStore[i].latitude,
            longitude: newTempAllStore[i].longitude,
            active: false
          })
        }
      }
      var newTempData = [];
      if (tempData.length > 10) {
        for (let i = 0; i < 10; i++) {
          newTempData.push(tempData[i])
        }
      } else {
        for (let i = 0; i < tempData.length; i++) {
          newTempData.push(tempData[i])
        }
      }
      console.log(newTempData)
      this.setData({
        storeList: newTempData,
        allStoreList: tempData,
        noStoreData: false,
        refresh: false
      })
    } catch (e) {
      console.log(e)
    }
  },
  // 根据坐标获取当前位置名称，使用腾讯地图逆地址解析
  danleStoreListInfo(self, latitude, longitude) {
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        console.log(res)
        self.setData({
          // 获取经过腾讯地图优化过的地理位置描述
          currentAddress: res.result.formatted_addresses.recommend
        })
      },
      fail: function (res) {
        console.log(res);
      }
    })
    self.hadleStoreOrder(latitude, longitude);

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(options)
    var self = this;
    var latitude = "";
    var longitude = "";
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'AD5BZ-CHCKS-64OOD-6G6TX-BSOA6-IFF3V'
    });

    if (options.name && options.lat && options.lng) {
      app.globalData.addressInfo = options;
      latitude = options.lat;
      longitude = options.lng;
      this.setData({
        currentAddress: options.name
      })
      self.danleStoreListInfo(self, latitude, longitude);
    } else if (!options.name && app.globalData.addressInfo) {
      latitude = app.globalData.addressInfo.lat;
      longitude = app.globalData.addressInfo.lng;
      this.setData({
        currentAddress: app.globalData.addressInfo.name
      })
      self.danleStoreListInfo(self, latitude, longitude);
    } else {
      //1、获取当前位置坐标
      wx.getLocation({
        type: 'gcj02',
        success: function (res) {
          latitude = res.latitude
          longitude = res.longitude
          // 2.根据当前位置，获取最近的几个门店信息
          self.danleStoreListInfo(self, latitude, longitude);
        }
      })
    }
  },
  // 门店点击事件
  clickStore: function (e) {
    console.log(e)
    this.data.storeList.forEach((item, index) => {
      if (e.currentTarget.dataset.key == index) {
        item.active = true;
        app.globalData.storeInfo = item;
      } else {
        item.active = false;
      }
    })
    this.setData({
      storeList: this.data.storeList
    })
    wx.navigateBack({
      url: '../coupon/couponCenter/couponCenter',
    })
  },
  // 监听搜索框输入
  handleInput: function (e) {
    if (!e.detail.value) {
      var tempStoreList = [];
      var allStores = wx.getStorageSync('wj_allStores'); // 获取缓存的所有门店
      for (let i = 0; i < 10; i++) {
        tempStoreList.push({
          id: allStores[i].id,
          name: allStores[i].name,
          address: allStores[i].address,
          distance: allStores[i].distance.toFixed(2),
          latitude: allStores[i].latitude,
          longitude: allStores[i].longitude,
          active: false
        })
      }
      this.setData({
        storeList: tempStoreList
      })
    }
  },
  // 搜索框失去焦点处理
  handleConfirm: function (e) {
    console.log(e)
    if (!e.detail.value) {
      this.setData({
        searchLabelShow: false
      })
      var tempStoreList = [];
      var allStores = wx.getStorageSync('wj_allStores'); // 获取缓存的所有门店
      for (let i = 0; i < 10; i++) {
        tempStoreList.push({
          id: allStores[i].id,
          name: allStores[i].name,
          address: allStores[i].address,
          distance: allStores[i].distance.toFixed(2),
          latitude: item.latitude,
          longitude: item.longitude,
          active: false
        })
      }
      this.setData({
        storeList: tempStoreList,
      })
    } else {
      this.setData({
        searchLabelShow: true
      })
      console.log(e.detail.value)
      var tempStoreList = [];
      var allStores = wx.getStorageSync('wj_allStores'); // 获取缓存的所有门店
      var reg = new RegExp(e.detail.value);
      allStores.forEach(item => {
        if (reg.test(item.name)) {
          console.log(item)
          tempStoreList.push({
            id: item.id,
            name: item.name,
            address: item.address,
            distance: item.distance.toFixed(2),
            latitude: item.latitude,
            longitude: item.longitude,
            active: false
          })
        }
      })
      this.setData({
        storeList: tempStoreList
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    try {
      // wx.removeStorageSync('wj_allStores')
    } catch (e) {
      // Do something when catch error
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      noStoreData: true,
      refresh: true,
    })
    this.getAllStoreList()
    var newTempAllStore = this.data.allStoreList;

    var tempData = [];
    if (newTempAllStore.length > 0) {
      for (let i = 0; i < 10; i++) {
        tempData.push(newTempAllStore[i])
      }
    } else {
      tempData = []
      console.log("1")
    }
    this.setData({
      storeList: tempData,
      page: 0,

    });
    console.log(tempData)
    wx.stopPullDownRefresh()
  },
  //获取所有门店列表
  getAllStoreList: function () {
    const self = this
    var latitude = "";
    var longitude = "";
    const tempAllStoreList = self.data.allStoreList
    this.setData({
      storeList: [],
      allStoreList: [],
      page: 0
    });
    storeService.queryList().then(res => {
      console.log(res)

      var allStores = [];
      res.forEach(item => {
        if (item.status === 'OPEN') {
          allStores.push(item)
        }
      });
      try {
        wx.removeStorageSync('wj_allStores')
        wx.setStorageSync('wj_allStores', allStores)
        if (self.options.name && self.options.lat && self.options.lng) {
          app.globalData.addressInfo = self.options;
          latitude = self.options.lat;
          longitude = self.options.lng;
          this.setData({
            currentAddress: self.options.name
          })
          self.danleStoreListInfo(self, latitude, longitude);
        } else if (!self.options.name && app.globalData.addressInfo) {
          latitude = app.globalData.addressInfo.lat;
          longitude = app.globalData.addressInfo.lng;
          this.setData({
            currentAddress: app.globalData.addressInfo.name
          })
          self.danleStoreListInfo(self, latitude, longitude);
        } else {
          //1、获取当前位置坐标
          wx.getLocation({
            type: 'gcj02',
            success: function (res) {
              latitude = res.latitude
              longitude = res.longitude
              // 2.根据当前位置，获取最近的几个门店信息
              self.danleStoreListInfo(self, latitude, longitude);

            }
          })
        }
      } catch (e) {
        console.log(e)
        wx.showToast({
          title: e.message,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // this.loadList()
  },

  /**
   * 上拉加载
   */
  loadList: function () {
    var that = this
    that.setData({
      loading: true
    })
    var result = []
    var newAllStoreList = this.data.allStoreList
    var tempStoreList = this.data.storeList
    var newStoreList = []
    var index = this.data.page
    const count = Math.ceil(newAllStoreList.length / 10)
    if (index === count) {
      wx.showToast({
        title: '已经加载到底了~',
        icon: 'none',
        duration: 2000
      })
    } else {
      for (let i = 0; i < newAllStoreList.length; i += 10) {
        result.push(newAllStoreList.slice(i, i + 10))
      }
      index++
      newStoreList = tempStoreList.concat(result[index])
      console.log(newStoreList)

      setTimeout(() => {
        that.setData({
          storeList: newStoreList,
          page: index,
        });
      }, 500);
      that.setData({
        loading: false
      })
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  // 去选择地址
  toSelectAddress: function () {
    const self = this
    wx.chooseLocation({
      success: function (res) {
        // success
        console.log(res)
        self.setData({
          currentAddress: res.name
        })
        self.hadleStoreOrder(res.latitude, res.longitude);
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete
      }
    })
  },
})